package qdu.edu.com.fushanf4.service.sort.twosort;

import org.apache.hadoop.io.WritableComparable;
import org.jetbrains.annotations.NotNull;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

public class TextAndIntWritableBean implements WritableComparable<TextAndIntWritableBean> {
    private String firstCharacter; // 二字词语的第一个字
    private String twoCharacters; // 二字词语
    private int count;  // 二字词语的出现次数，权重

    public TextAndIntWritableBean() {
    }

    public void set(String twoCharacters, String count) {
        this.firstCharacter = twoCharacters.substring(0,1);
        this.twoCharacters = twoCharacters;
        this.count = Integer.parseInt(count);
    }

    @Override
    public int compareTo(@NotNull TextAndIntWritableBean o) {
        int result = 0;

        if (!this.firstCharacter.equals(o.firstCharacter)) {
            result = this.firstCharacter.compareTo(o.firstCharacter);
        } else if (this.count != o.count) {
            result = this.count > o.count ? -1 : 1; // 降序，不是升序，根据实际运行结果改正
        }

        return result;
    }

    @Override
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeUTF(firstCharacter);
        dataOutput.writeUTF(twoCharacters);
        dataOutput.writeInt(count);
    }

    @Override
    public void readFields(DataInput dataInput) throws IOException {
        firstCharacter = dataInput.readUTF();
        twoCharacters = dataInput.readUTF();
        count = dataInput.readInt();
    }

    public String getTwoCharacters() {
        return twoCharacters;
    }
}
